package com.useeinfo.oa.modules.base.biz;

import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.oa.modules.base.dao.FacilityGroupDao;
import com.useeinfo.oa.modules.base.entity.FacilityGroup;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Auther: bin.liu
 * @Date: 2018/12/5 9:56
 * @Description: 设备分组管理service
 */
@Service
public class FacilityGroupBiz extends CrudBiz<FacilityGroupDao, FacilityGroup> {

    public Boolean existFacilityGroupName(FacilityGroup facilityGroup, Long enterpriseId) {
        if (StringUtils.isBlank(facilityGroup.getFacilityGroupName())) {
            return true;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");
        queryParam.getSqlMap().put("groupName", facilityGroup.getFacilityGroupName());
        List<FacilityGroup> facilityGroupList = this.findList(queryParam);

        if (facilityGroup.getId() == null) {
            return CollectionUtils.isNotEmpty(facilityGroupList);
        } else {
            return (!((facilityGroupList.size() == 1 && facilityGroupList.get(0).getId().equals(facilityGroup.getId())) || facilityGroupList.size() == 0));
        }
    }


    /**
     * 获取设备分组编号
     *
     * @param enterpriseId
     * @return
     */
    public String getGroupCode(String enterpriseId) {
        String groupCode = enterpriseId + "-" + DateTimeUtils.formatDateToStringWithOnlyDate(new Date(), "yyyyMMdd") + "-" + (int) ((Math.random() * 9 + 1) * 100000);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("groupCode", groupCode);
        List<FacilityGroup> facilityGroupList = this.findList(queryParam);
        if (CollectionUtils.isNotEmpty(facilityGroupList)) {
            return getGroupCode(enterpriseId);
        } else {
            return groupCode;
        }
    }

    /**
     * 根据名称判断是否有该设备分组(有返回 没有返回NULL)
     *
     * @param enterpriseId
     * @return
     */
    public FacilityGroup getFacilityGroupByName(String groupName,String enterpriseId) {
        if(StringUtils.isBlank(groupName)||StringUtils.isBlank(enterpriseId)){
            return null;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");
        queryParam.getSqlMap().put("groupName", groupName);
        List<FacilityGroup> facilityGroupList = this.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityGroupList)){
            return facilityGroupList.get(0);
        }
        return null;
    }
}
